<template>
  <div class="login">
    <div class="login-container">
      <div class="title-container">
        <h3 class="title">登录</h3>
      </div>
      <Form ref="loginForm" class="login-form">
        <FormItem prop="username">
          <Input
              ref="username"
              v-model="loginForm.username"
              placeholder="管理员用户名"
              name="username"
              type="text"
              tabindex="1"
              auto-complete="on"
              class="input-item"
          >
            <Icon type="ios-person-outline" slot="prepend"></Icon>
          </Input>
        </FormItem>
        <FormItem prop="password">
          <Input
              :key="passwordType"
              ref="password"
              v-model="loginForm.password"
              :type="passwordType"
              placeholder="管理员密码"
              name="password"
              tabindex="2"
              auto-complete="on"
              class="input-item"
          >
            <Icon type="ios-lock-outline" slot="prepend"></Icon>
          </Input>
        </FormItem>
        <Button :loading="loading" type="primary" style="width:100%;margin-bottom:30px;" @click.native.prevent="handleLogin">Login</Button>
      </Form>
    </div>
  </div>
</template>

<script>
import Api from "@/api/user";
import { Storage } from "@/utils/storage";
export default {
  name: 'Login',
  data() {
    return {
      loginForm: {
        username: '',
        password: ''
      },
      loading: false,
      passwordType: 'password'
    }
  },
  methods: {
    handleLogin () {
      if (this.loginForm.username == null || this.loginForm.username === '' || this.loginForm.password == null || this.loginForm.password === '') {
        this.$Message.error('数据缺失')
        return
      }
      Api.login({name: this.loginForm.username, password: this.loginForm.password}).then(
          res => {
            const userData = res.data.data
            if (res.data.resultCode !== 200) {
              this.$Message.error(res.data.message)
              return
            }
            Storage.setItem('user_info', userData)
            Storage.setItem('TOKEN', res.headers.token)
            this.$Message.success('登录成功')
            this.$router.replace('/')
          }
      ).catch(
          () => {
            this.$Message.error('登录失败')
          }
      )
    }
  }
}
</script>

<style lang="scss" scoped>
.login {
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  .login-container {
    width: 500px;
    height: 300px;
    display: flex;
    flex-direction: column;
    justify-content: flex-start;
    align-items: center;
    .title-container {
      font-weight: 700;
      font-size: 30px;
      text-align: center;
      margin-bottom: 40px;
    }
    .login-form {
      width: 500px;
    }
  }
}
</style>
